/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gestion;

import java.awt.Color;
import java.awt.event.ItemEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import otros.Fecha;
import otros.MiTableModel;
import otros.Util;
import tablasSql.FacturasAlbaranes;
import tablasSql.Sql;

/**
 *
 * @author FERRETERIA
 */

public class FNegro extends javax.swing.JInternalFrame {    
    boolean fuera;
    int filaSel;
     
    public FNegro() {
        initComponents();
        tabla.setAutoCreateRowSorter(true);
        tabla.setColumnSelectionAllowed(false);
        String []fecha = new Fecha().getFecha().split("-");
        //txtDia.setText(fecha[0]);
        //txtMes.setText(fecha[1]);
        txtAño.setText(fecha[2]);
        ActualizarTabla();
        Colorear();
    }

    private void Colorear() {
        Color color = Util.getColorTicket(cbTipo.getSelectedItem().toString());
        cbTipo.setBackground(color);
        cbTipoPago.setBackground(color);
        txtAño.setBackground(color);
        txtDia.setBackground(color);
        txtMes.setBackground(color);
        txtIdCliente.setBackground(color);
    }
    
    private void AnchoColumnas() {
        DefaultTableColumnModel colModel = (DefaultTableColumnModel)tabla.getColumnModel();
        TableColumn col = colModel.getColumn(0);        
        col.setPreferredWidth(150);
        col = colModel.getColumn(1);
        col.setPreferredWidth(320);
        int valor = 25;
        tabla.getColumnModel().getColumn(4).setMaxWidth(valor);
        tabla.getColumnModel().getColumn(4).setMinWidth(valor);
        tabla.getColumnModel().getColumn(4).setPreferredWidth(valor);    

        
        bConvertir.setEnabled(false);
    }
    
    private void ActualizarTabla() {  
        int tipo = cbTipoPago.getSelectedIndex();
        int idCliente = Integer.parseInt(txtIdCliente.getText().isEmpty()? "-1" : txtIdCliente.getText());
        int dia = Integer.parseInt(txtDia.getText().isEmpty()? "0" : txtDia.getText());
        int mes = Integer.parseInt(txtMes.getText().isEmpty()? "0" : txtMes.getText());
        int año = Integer.parseInt(txtAño.getText().isEmpty()? "0" : txtAño.getText());
        int tam = tabla.getRowCount();
        for (int i = 0; i < tam; i++)
            ((DefaultTableModel)tabla.getModel()).removeRow(0); 
        MiTableModel datos = FacturasAlbaranes.getTabla(false, cbTipo.getSelectedIndex()
                                                    , 0, tipo, idCliente, dia, mes, año);
        datos.addColumn("", new Vector<Boolean>());
        datos.setType(new Class[] {String.class, String.class, Float.class, String.class, Boolean.class});
        datos.setEditable(new Boolean[] {false,false,false,false,true});
        
       
        tabla.setModel(datos);
        tabla.getColumnModel().getColumn(0).setCellRenderer(new tableCellRender.Id(filaSel, fuera,0));
        tabla.getColumnModel().getColumn(1).setCellRenderer(new tableCellRender.Texto(filaSel, fuera));
        tabla.getColumnModel().getColumn(2).setCellRenderer(new tableCellRender.Precio(filaSel, fuera));
        tabla.getColumnModel().getColumn(3).setCellRenderer(new tableCellRender.Fecha(filaSel, fuera));
        AnchoColumnas();
        HallarTotal();
    }
    
    private void Borrar(String valor) {
       int id = FacturasAlbaranes.getIdFacturaAlbaran(valor.substring(5), valor.substring(0,4),cbTipo.getSelectedIndex());
       Util.restaurarStock(id, cbTipo.getSelectedIndex(), true);
       FacturasAlbaranes.borrarFactAlbaran(id, cbTipo.getSelectedIndex());
       FacturasAlbaranes.borrarListArticulos(id, cbTipo.getSelectedIndex());
    }
    
    private void Convertir (int aConvertir) {
        boolean primero = true;
        int newIdT = -1;
        String newId = ""+new Fecha().getAño();
        int pos = 0;
        if (tabla.isEditing())
            tabla.editingStopped(null);
        for (int i = 0; i < tabla.getRowCount(); i++) {
            if ((tabla.getValueAt(i,4) != null) && ((Boolean) tabla.getValueAt(i, 4)).booleanValue()) {
                String valor = "" + tabla.getValueAt(i, 0);
                int id = FacturasAlbaranes.getIdFacturaAlbaran(valor.substring(5), valor.substring(0,4),cbTipo.getSelectedIndex());
                if (primero) {      // primer albaran a pasar
                    primero = false;
                    ResultSet res = FacturasAlbaranes.getFacturaAlbaran(id, cbTipo.getSelectedIndex());
                    try {
                        if (!res.next()) {
                            return ;  
                        }
                        String sqlTabla = FacturasAlbaranes.getTablaSql(aConvertir);
                        int idImp = Sql.getMax("idImp",sqlTabla)+1;
                        String datos [] = { new Fecha().getFechaSQL()+ " " + new Fecha().getHora(),
                                       res.getString("observacion"),
                                       "" + res.getFloat("total"), 
                                       "" + res.getInt("descuento"), 
                                       "" + res.getFloat("totalmano"),
                                       "" + res.getInt("idCliente"),
                                       "1", //+ res.getInt("tipopago"),         //credito
                                       "" + idImp
                                       };        
                        // paso el albaran a factura
                         newIdT = FacturasAlbaranes.guardar(datos, true, aConvertir);  
                         DecimalFormat df = new DecimalFormat("000000");
                         newId += "-"+df.format(idImp);
                    } catch (SQLException ex) {
                        System.out.println("error en ffacturas.convertir");
                    }
                }
                
                // borro albaran o presupuesto
                FacturasAlbaranes.borrarFactAlbaran(id, cbTipo.getSelectedIndex());
            
                //inserto el numero de albaran en la lista
                if(cbTipo.getSelectedIndex()==1) {
                    DecimalFormat df = new DecimalFormat("000000");
                    String [] fecha =  tabla.getValueAt(i, 3).toString().substring(0,10).split("-");
                    String datos3 [] = {cbTipo.getSelectedItem().toString() + " nº: " +
                                        valor.substring(0,4)+"-"+df.format(Integer.parseInt(valor.substring(5))) +
                                         " Fecha: " + fecha[2] + "/" + fecha[1] + "/" + fecha[0], //detalle
                                        null, //margen
                                        null, //descuento
                                        null, //precio
                                        null, //total
                                        null, //cantidad
                                        null,
                                        "0",
                                        ""+pos, //pos
                                        ""+newIdT,
                                   };
                    FacturasAlbaranes.guardarLista(datos3);
                }
                
                // modifico los articulos
                String datos2[] = {""+newIdT, ""+aConvertir,""+(pos++), "" + id, ""+cbTipo.getSelectedIndex()}; 
                pos += FacturasAlbaranes.convertir(datos2);
            }  
        }
        if (newIdT != -1)
            abrirFactura(newId, aConvertir);
    }
    
    
    private void abrirFactura(String id, int tipo) {
        FTPV tpv = new FTPV();
        this.getParent().add(tpv);
        Principal.centrarFrame(tpv);
        tpv.show();    
        tpv.cargar(id, tipo);
    }
    
    private void HallarTotal() {
        float total = 0;
        for(int i = 0; i < tabla.getRowCount(); i++) {
            total += Float.parseFloat(tabla.getValueAt(i, 2).toString());
        }
        txtTotal.setText(Util.getFormatPrecio(total,2));
    }
    
    private void Sumar() {
        float total = 0;
        for(int i = 0; i < tabla.getRowCount(); i++) {
            if ((tabla.getValueAt(i, 4) != null) && ((Boolean)tabla.getValueAt(i, 4)))
                total += Float.parseFloat(tabla.getValueAt(i, 2).toString());
        }
        txtSuma.setText(Util.getFormatPrecio(total,2));
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbTipo = new javax.swing.JComboBox();
        txtIdCliente = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        cbTipoPago = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        txtDia = new javax.swing.JFormattedTextField();
        jLabel3 = new javax.swing.JLabel();
        txtMes = new javax.swing.JFormattedTextField();
        bBuscar = new javax.swing.JButton();
        txtAño = new javax.swing.JFormattedTextField();
        jLabel4 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        bConvertir = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        txtSuma = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        txtTotal = new javax.swing.JTextField();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Gestion Ventas");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icono2.png"))); // NOI18N
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setMinimumSize(new java.awt.Dimension(250, 250));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(250, 250));

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Cliente", "Total", "Fecha", ""
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabla.setColumnSelectionAllowed(true);
        tabla.getTableHeader().setReorderingAllowed(false);
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                tablaMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                tablaMouseExited(evt);
            }
        });
        tabla.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseMoved(java.awt.event.MouseEvent evt) {
                tablaMouseMoved(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);
        tabla.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        if (tabla.getColumnModel().getColumnCount() > 0) {
            tabla.getColumnModel().getColumn(0).setResizable(false);
            tabla.getColumnModel().getColumn(1).setResizable(false);
            tabla.getColumnModel().getColumn(2).setResizable(false);
            tabla.getColumnModel().getColumn(3).setResizable(false);
            tabla.getColumnModel().getColumn(4).setResizable(false);
        }

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        jPanel1.setMinimumSize(new java.awt.Dimension(400, 70));
        jPanel1.setPreferredSize(new java.awt.Dimension(400, 70));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Criterios de busqueda:   ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 5, 0);
        jPanel1.add(jLabel1, gridBagConstraints);

        cbTipo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Factura", "Albaran", "Presupuesto" }));
        cbTipo.setEnabled(false);
        cbTipo.setMinimumSize(new java.awt.Dimension(100, 20));
        cbTipo.setPreferredSize(new java.awt.Dimension(100, 20));
        cbTipo.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTipoItemStateChanged(evt);
            }
        });
        cbTipo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                cbTipoKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        jPanel1.add(cbTipo, gridBagConstraints);

        txtIdCliente.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtIdCliente.setMinimumSize(new java.awt.Dimension(100, 20));
        txtIdCliente.setPreferredSize(new java.awt.Dimension(40, 20));
        txtIdCliente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtIdClienteMouseClicked(evt);
            }
        });
        txtIdCliente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtIdClienteKeyPressed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0);
        jPanel1.add(txtIdCliente, gridBagConstraints);

        jLabel6.setText("Id Cliente");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 5);
        jPanel1.add(jLabel6, gridBagConstraints);

        cbTipoPago.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Todos", "Contado", "Credito" }));
        cbTipoPago.setSelectedIndex(1);
        cbTipoPago.setEnabled(false);
        cbTipoPago.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbTipoPagoItemStateChanged(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        jPanel1.add(cbTipoPago, gridBagConstraints);

        jLabel2.setText("Dia");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(jLabel2, gridBagConstraints);

        txtDia.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("00"))));
        txtDia.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtDia.setMinimumSize(new java.awt.Dimension(25, 20));
        txtDia.setPreferredSize(new java.awt.Dimension(25, 20));
        txtDia.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtDiaMouseClicked(evt);
            }
        });
        txtDia.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtDiaKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(txtDia, gridBagConstraints);

        jLabel3.setText("Mes");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 4;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(jLabel3, gridBagConstraints);

        txtMes.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("00"))));
        txtMes.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtMes.setMinimumSize(new java.awt.Dimension(25, 20));
        txtMes.setPreferredSize(new java.awt.Dimension(25, 20));
        txtMes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtMesMouseClicked(evt);
            }
        });
        txtMes.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtMesKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 5;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(txtMes, gridBagConstraints);

        bBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/buscar.png"))); // NOI18N
        bBuscar.setMinimumSize(new java.awt.Dimension(61, 61));
        bBuscar.setPreferredSize(new java.awt.Dimension(61, 61));
        bBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bBuscarActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 8;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 3;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(bBuscar, gridBagConstraints);

        txtAño.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("0000"))));
        txtAño.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtAño.setToolTipText("yyyy");
        txtAño.setMinimumSize(new java.awt.Dimension(25, 20));
        txtAño.setPreferredSize(new java.awt.Dimension(35, 20));
        txtAño.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtAñoMouseClicked(evt);
            }
        });
        txtAño.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtAñoKeyReleased(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 7;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(txtAño, gridBagConstraints);

        jLabel4.setText("Año");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 6;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 0);
        jPanel1.add(jLabel4, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.ipadx = 175;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 10, 0, 10);
        getContentPane().add(jPanel1, gridBagConstraints);

        jPanel2.setPreferredSize(new java.awt.Dimension(160, 60));
        jPanel2.setLayout(new java.awt.GridBagLayout());

        bConvertir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/factura.png"))); // NOI18N
        bConvertir.setToolTipText("<html><p align=center>El albaran o albaranes se convierte <br> a factura eliminando los albaranes</p>");
        bConvertir.setMinimumSize(new java.awt.Dimension(60, 60));
        bConvertir.setPreferredSize(new java.awt.Dimension(60, 60));
        bConvertir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bConvertirActionPerformed(evt);
            }
        });
        jPanel2.add(bConvertir, new java.awt.GridBagConstraints());

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
        getContentPane().add(jPanel2, gridBagConstraints);

        jPanel3.setPreferredSize(new java.awt.Dimension(160, 60));
        jPanel3.setLayout(new java.awt.GridBagLayout());

        txtSuma.setEditable(false);
        txtSuma.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtSuma.setMinimumSize(new java.awt.Dimension(100, 20));
        txtSuma.setPreferredSize(new java.awt.Dimension(100, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        jPanel3.add(txtSuma, gridBagConstraints);

        jLabel8.setText("Suma");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        jPanel3.add(jLabel8, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 10);
        getContentPane().add(jPanel3, gridBagConstraints);

        jPanel4.setMinimumSize(new java.awt.Dimension(100, 80));
        jPanel4.setPreferredSize(new java.awt.Dimension(200, 60));
        jPanel4.setLayout(new java.awt.GridBagLayout());

        jLabel7.setText("Total");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 0;
        jPanel4.add(jLabel7, gridBagConstraints);

        txtTotal.setEditable(false);
        txtTotal.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtTotal.setMinimumSize(new java.awt.Dimension(100, 20));
        txtTotal.setPreferredSize(new java.awt.Dimension(100, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 3;
        gridBagConstraints.gridy = 1;
        jPanel4.add(txtTotal, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
        getContentPane().add(jPanel4, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == 34) {
            int i = cbTipo.getSelectedIndex();
            if (i > cbTipo.getItemCount()) 
               i = 0;
            else
                i++;
            cbTipo.setSelectedIndex(i);
        }
    }//GEN-LAST:event_formKeyPressed

    private void cbTipoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_cbTipoKeyPressed
        if (evt.getKeyCode() == 10) 
            cbTipo.transferFocus();
    }//GEN-LAST:event_cbTipoKeyPressed

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
        int fila = tabla.rowAtPoint(evt.getPoint());
        int columna = tabla.columnAtPoint(evt.getPoint());
        
        if (evt.getClickCount() == 2) {
           abrirFactura(""+tabla.getValueAt(tabla.getSelectedRow(), 0), cbTipo.getSelectedIndex());
        }
        if (columna ==4) {
           Boolean valor = false;
           for (int i = 0; (i < tabla.getRowCount()) && !valor; i++) {
               if (Boolean.parseBoolean(""+tabla.getValueAt(i, 4))) {
                   valor = Boolean.parseBoolean(""+tabla.getValueAt(i, 4));
               }
           }
           bConvertir.setEnabled(valor);
            Sumar();
        }
        
    }//GEN-LAST:event_tablaMouseClicked

    private void txtIdClienteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtIdClienteKeyPressed
        switch (evt.getKeyCode()) {
            case 113:
                FClientes c = new FClientes(this, Util.FFACTURAS);
                this.getParent().add(c);
                Principal.centrarFrame(c);
                c.show();
                break;
            case 10:
                ActualizarTabla();
                break;
        }
    }//GEN-LAST:event_txtIdClienteKeyPressed

    private void tablaMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseExited
        fuera = true;
    }//GEN-LAST:event_tablaMouseExited

    private void tablaMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseEntered
        fuera = false;
    }//GEN-LAST:event_tablaMouseEntered

    private void tablaMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseMoved
        JTable aTable =  (JTable)evt.getSource();
        if (!fuera) {
            filaSel = aTable.rowAtPoint(evt.getPoint());
        }
    }//GEN-LAST:event_tablaMouseMoved

    private void bBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bBuscarActionPerformed
        ActualizarTabla();
    }//GEN-LAST:event_bBuscarActionPerformed

    private void txtIdClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtIdClienteMouseClicked
        txtIdCliente.selectAll();
    }//GEN-LAST:event_txtIdClienteMouseClicked

    private void txtDiaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtDiaMouseClicked
        txtDia.selectAll();
    }//GEN-LAST:event_txtDiaMouseClicked

    private void txtMesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtMesMouseClicked
        txtMes.selectAll();
    }//GEN-LAST:event_txtMesMouseClicked

    private void bConvertirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bConvertirActionPerformed
        switch (cbTipo.getSelectedIndex()){
            case 1:
                if(JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(null, 
                                                "¿Esta seguro? (los albaranes seran borrados)",
                                                "Transformar a Factura", JOptionPane.OK_CANCEL_OPTION)) {
                    Convertir(0);
                }
                break;
            case 2:
                int seleccion = JOptionPane.showOptionDialog(this, "Seleccione opcion", "En que se convertira", 
                                    JOptionPane.YES_NO_CANCEL_OPTION,                    
                                    JOptionPane.QUESTION_MESSAGE,
                                    null,    // null para icono por defecto.
                                    new Object[] { "Factura", "Albaran"},   // null para YES, NO y CANCEL
                                    "Factura");
                if (seleccion != -1) 
                    Convertir(seleccion);
                break;
        }
        ActualizarTabla();
    }//GEN-LAST:event_bConvertirActionPerformed

    private void cbTipoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTipoItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            ActualizarTabla();
            Colorear();
        }
    }//GEN-LAST:event_cbTipoItemStateChanged

    private void txtAñoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtAñoMouseClicked
        txtAño.selectAll();
    }//GEN-LAST:event_txtAñoMouseClicked

    private void txtAñoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtAñoKeyReleased
        if (evt.getKeyCode() == 10) {
            ActualizarTabla();
        }
    }//GEN-LAST:event_txtAñoKeyReleased

    private void txtDiaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtDiaKeyReleased
        if (evt.getKeyCode() == 10) {
            ActualizarTabla();
            txtMes.requestFocus();
        }
    }//GEN-LAST:event_txtDiaKeyReleased

    private void txtMesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtMesKeyReleased
        if (evt.getKeyCode() == 10) {
            ActualizarTabla();
            txtAño.requestFocus();
        }
    }//GEN-LAST:event_txtMesKeyReleased

    private void cbTipoPagoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbTipoPagoItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            ActualizarTabla();
        }
    }//GEN-LAST:event_cbTipoPagoItemStateChanged

         
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bBuscar;
    private javax.swing.JButton bConvertir;
    private javax.swing.JComboBox cbTipo;
    private javax.swing.JComboBox cbTipoPago;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabla;
    private javax.swing.JFormattedTextField txtAño;
    private javax.swing.JFormattedTextField txtDia;
    public javax.swing.JTextField txtIdCliente;
    private javax.swing.JFormattedTextField txtMes;
    private javax.swing.JTextField txtSuma;
    private javax.swing.JTextField txtTotal;
    // End of variables declaration//GEN-END:variables
}
